<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Pesan_model extends CI_Model {

    function __construct() {
        parent::__construct();
    }

    function get_pesan_terakhir($phone) {
        $query = $this->db->query("select k.*,m.nama_kontak,m.group_kontak from komplain k left join kontak_member m on k.sender = m.notelp_kontak AND m.id_member_owner = ? where k.sender =? "
                . " and upper(k.isi) <> 'CEK' and k.date_created >= date_sub(now(), interval 1 day) "
                . " and k.receiver in (select port from kepemilikan_port where id_member = ?)"
                . " order by k.id_komplain", array($this->session->userdata('id_member'), $phone, $this->session->userdata('id_member')));
        $result = $query->result();
        return $result;
    }

    function get_pesan_baru() {
        $query = $this->db->query("select count(id_komplain) as jumlah "
                . "from komplain where date_created = curdate() and status = 0 "
                . "and upper(isi) <> 'CEK' and receiver in "
                . "(select port from kepemilikan_port where id_member = ?)", array($this->session->userdata('id_member')));
        $result = $query->result();
        foreach ($result as $data) {
            return $data->jumlah;
        }
        return 0;
    }

    function jawab_pesan($jawaban, $id_komplain) {
        $query = "update komplain set jumlah_respon = jumlah_respon + 1, jawaban = concat(jawaban,?), status=1 where id_komplain = ?";
        $this->db->query($query, array("|" . $jawaban . "<br/><i>(dikirim pukul : " . date('Y-m-d H:i:s', strtotime("now")) . ")</i>", $id_komplain));

        $query = $this->db->query("select sender, receiver from komplain where id_komplain=?", array($id_komplain));
        $result = $query->result();
        foreach ($result as $data) {
            $query = "insert into message_outbox (receiver,content,date_created,id_member,is_sent, id_modul) values (?,?,now(),?,0, ?)";
            $this->db->query($query, array($data->sender, $jawaban, $this->session->userdata("id_member"), $data->receiver));
            return json_encode(array("err_code" => "00", "msg" => "Pesan berhasil dikirimkan"));
        }

        return json_encode(array("err_code" => "20", "msg" => "Data Komplain tidak ditemukan"));
    }

    function insert_outbox($pesan, $sender, $id_member, $id_modul) {
        $query = "insert into message_outbox (receiver,content,date_created,id_member,is_sent, id_modul) values (?,?,now(),?,0, ?)";
        $this->db->query($query, array($sender, $pesan, $id_member, $id_modul));
    }

}

?>